package com.example.todolist

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.StringBuilder
import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    val TAG = "@@MAIN"

    lateinit var helper: DBHelper
    lateinit var adapter: TodoAdapter

    private var toUpdate:Todo?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
    }

    private fun init() {
        helper = DBHelper(this, "todo.db", 1)

        adapter = TodoAdapter()

        val recycler = findViewById<RecyclerView>(R.id.recycler)
        recycler.layoutManager = LinearLayoutManager(this)
        recycler.adapter = adapter


        readInDb()

        findViewById<Button>(R.id.btn_save).setOnClickListener {
            saveInput()
        }

        findViewById<Button>(R.id.btn_conveyDelete).setOnClickListener{
            toDelete()
        }
    }

    private fun toDelete() {
        val intent =Intent(this,delete::class.java)
        startActivity(intent)
    }

    @SuppressLint("Range")
    private fun readInDb() //从数据库中查询数据，并显示
    {
        val db = helper.readableDatabase
        val cursor = db.query(
            Todo.TABLE, null, null, null, null, null,
            "${Todo.COL_ID} desc "
        )
        val arr = arrayListOf<Todo>()
        if (cursor.moveToFirst()) {
            do {
                arr.add(
                    Todo(
                        cursor.getString(cursor.getColumnIndex(Todo.COL_CONTENT)),
                        cursor.getLong(cursor.getColumnIndex(Todo.COL_TIME)),
                    ).apply {
                        id = cursor.getInt(cursor.getColumnIndex(Todo.COL_ID))
                    }
                )
            } while (cursor.moveToNext())
        }
        adapter.setData(arr)
        cursor.close()
    }


    private fun saveInput() {
        val text = findViewById<EditText>(R.id.ipt_text).text.toString()
        saveInDb(text)
    }

    private fun saveInDb(text: String) {
        val db = helper.writableDatabase
        val item = Todo(text,System.currentTimeMillis())
        val values = ContentValues().apply {
            put(Todo.COL_CONTENT, text)
            put(Todo.COL_TIME, System.currentTimeMillis())
        }
        var rs=-1

        if(toUpdate!=null){
            item.id=toUpdate?.id
            rs=db.update(Todo.TABLE,values,"id=?", arrayOf(toUpdate?.id.toString()))
            if(rs!=-1)
            {
                adapter.replaceItem(toUpdate?.id,item)
                toUpdate=null
            }
        }else{
            rs=db.insert(Todo.TABLE, null, values).toInt()
            if(rs!=-1){
                item.id=rs
                adapter.addItem(item)
            }
        }

        Toast.makeText(this, if (rs < 0) "保存失败" else "保存成功", Toast.LENGTH_LONG).show()
        setInputText("")
    }


    inner class TodoAdapter : RecyclerView.Adapter<TodoViewHolder>() {

        val data = arrayListOf<Todo>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo, parent, false)

            return TodoViewHolder(view).apply {
                id = view.findViewById(R.id.id)
                content = view.findViewById(R.id.content)
                btnUpdate = view.findViewById(R.id.btn_update)
            }

        }

        override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
            holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun setData(arr: ArrayList<Todo>) {
            data.addAll(arr)
            notifyDataSetChanged()
        }

        fun replaceItem(id: Int?, item: Todo) {
            val idx =findIdx(id)
            if(idx>0){
                data.set(idx,item)
                notifyItemChanged(idx)
            }
        }

        private fun findIdx(id: Int?): Int {
            var idx=-1;
            data.forEachIndexed{
                index, todo ->
                if(todo.id==id)
                {
                    idx=index
                }
            }
            return idx
        }

        fun addItem(item: Todo) {
            data.add(0,item)
            notifyItemInserted(0)
        }
    }



    inner class TodoViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        var id: TextView? = null
        var content: TextView? = null
        var btnUpdate: TextView? = null

        fun render(todo: Todo) {

            id?.text = todo.id.toString()

            content?.text = todo.content

            btnUpdate?.setOnClickListener {
                Log.d(TAG,"to update id =${todo.id}")
                val db = helper.writableDatabase
                toUpdate=todo
                setInputText(todo.content)
            }
        }
    }

    private fun setInputText(content: String) {
        findViewById<EditText>(R.id.ipt_text).setText(content)
    }

//    fun onClick02(view: View) {
//        startActivity(Intent(this,delete::class.java))
//    }
}



//
////import android.annotation.SuppressLint
////import android.content.ContentValues
////import androidx.appcompat.app.AppCompatActivity
////import android.os.Bundle
////import android.view.LayoutInflater
////import android.view.ViewGroup
////import android.widget.Button
////import android.widget.EditText
////import android.widget.Toast
////import androidx.recyclerview.widget.LinearLayoutManager
////import androidx.recyclerview.widget.RecyclerView
//
//import android.annotation.SuppressLint
//import android.content.ContentValues
//import androidx.appcompat.app.AppCompatActivity
//import android.os.Bundle
//import android.util.Log
//import android.view.LayoutInflater
//import android.view.View
//import android.view.ViewGroup
//import android.widget.Button
//import android.widget.EditText
//import android.widget.TextView
//import android.widget.Toast
//import androidx.recyclerview.widget.LinearLayoutManager
//import androidx.recyclerview.widget.RecyclerView
//import java.io.BufferedReader
//import java.io.BufferedWriter
//import java.io.InputStreamReader
//import java.io.OutputStreamWriter
//import java.lang.StringBuilder
//import java.util.ArrayList
//
//
//
//class MainActivity : AppCompatActivity() {
//
//    lateinit var  helper : DBMS
//    lateinit var adapter :TodoAdapter
//
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main)
//        init()
//    }
//
//    private fun init(){
//        helper = DBMS(this,"todo.db",1)
//
//        adapter = TodoAdapter()
//
//        val recycler = findViewById<RecyclerView>(R.id.recycler)
//        recycler.layoutManager = LinearLayoutManager(this)
//        recycler.adapter = adapter
//
//        readInDb()
//
//        findViewById<Button>(R.id.saved).setOnClickListener {
//            saveInput()
//        }
//    }
//
//    @SuppressLint("Range")
//    private fun readInDb() {
//        val db = helper.readableDatabase
//        val cursor = db.query(todo.TABLE,null,null,null,null,null,
//            "${todo.C_TIME} desc ")
//        val arr = arrayListOf<todo>()
//        if(cursor.moveToFirst()){
//            do{
//                arr.add(
//                    todo(
//                        cursor.getString(cursor.getColumnIndex(todo.C_CONTENT)),
//                        cursor.getLong(cursor.getColumnIndex(todo.C_TIME)),
//                    ).apply {
//                        id = cursor.getInt(cursor.getColumnIndex(todo.C_ID))
//                    }
//                )
//            }while (cursor.moveToNext())
//        }
//
//        adapter.setData(arr)
//
//        cursor.close()
//    }
//
//    private fun saveInput() {
//        val text = findViewById<EditText>( R.id.saved).text.toString()
//        saveIndb(text)
//    }
//
//    private fun saveIndb(text: String) {
//        val db = helper.writableDatabase
//        val values = ContentValues().apply {
//            put(todo.C_CONTENT,text)
//            put(todo.C_TIME,System.currentTimeMillis())
//        }
//        val rs = db.insert(todo.TABLE,null,values)
//
//        Toast.makeText(this,if(rs < 0) "保存失败" else "保存成功" , Toast.LENGTH_LONG).show()
//
//        readInDb()
//
//    }
//
//
//
//
//    inner class TodoAdapter : RecyclerView.Adapter<TodoViewHolder>() {
//
//        val data  = arrayListOf<todo>()
//
//        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
//            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
//            return TodoViewHolder(view).apply {
//                id = view.findViewById(R.id.id)
//                content = view.findViewById(R.id.context)
//                btnUpdate = view.findViewById(R.id.update)
//                btnDelete = view.findViewById(R.id.delete)
//            }
//        }
//
//        override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
//            holder.render(data[position])
//        }
//
//        override fun getItemCount(): Int {
//            return data.size
//        }
//
//        fun setData(arr: ArrayList<todo>) {
//            data.addAll(arr)
//
//            notifyDataSetChanged()
//        }
//
//    }
//
//        inner class TodoViewHolder(view: View): RecyclerView.ViewHolder(view){
//
//            var id:TextView? = null
//            var content:TextView? = null
//
//            var btnDelete:TextView? = null
//            var btnUpdate:TextView? = null
//
//            fun render(todo: todo) {
//                id?.text = todo.id.toString()
//                content?.text = todo.content
//
//                btnDelete?.setOnClickListener {
//
//                }
//                btnDelete?.setOnClickListener {
//
//                }
//
//
//            }
//
//        }
//
//}